package com.shuaiche.yeguan.ui.common;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.fastjson.JSONObject;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.views.X5WebView;

public class WebviewActivity extends AppCompatActivity {

    private TextView toolbar_title;
    private Toolbar toolbar;

    private FrameLayout webviewContain;

    private X5WebView webView;

    private String bundleTitle;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        initViews();
    }

    private void initViews() {
        toolbar_title = findViewById(R.id.toolbar_title);
        toolbar = findViewById(R.id.toolbar);
        webviewContain = findViewById(R.id.webview);

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        bundleTitle = getIntent().getStringExtra("bundleTitle");
        url = getIntent().getStringExtra("url");

        confing();

        webView.loadUrl(url);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void confing() {
        webView = new X5WebView(this, null);
        webviewContain.addView(webView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));

        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setLoadWithOverviewMode(true);
//        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
//        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
//        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
//        webSetting.setAppCachePath(this.getActivity().getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);


        webSetting.setDefaultTextEncodingName("utf-8");

        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("tel:")) {
//                    telUrl = url;
//                    SCCallDialogFragment callDialog = new SCCallDialogFragment();
//                    callDialog.addValues("content", url.replace("tel:", ""));
//                    callDialog.addValues("confirm", ResourceUtils.getString(SCWebViewFragment.this.getContext(),
//                            R.string.btn_call_phone));
//                    callDialog.commitAddValues();
//                    callDialog.showAllowingStateLoss(SCWebViewFragment.this);
//                    callDialog.setConfirmListener(() -> {
//                        callPhone();
//                    });
                    return true;
                }
                webView.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                loadingView.showContent();
//                //维保订单查博士去掉title和底部bar
//                if (chaType) {
//                    String title = "javascript:function hideTitle() {"
//                            + "document.getElementsByTagName('body')[0].innerHTML;"
//                            + "document.getElementsByTagName('header')[0].style.display='none';}";
//
//                    String foot = "javascript:function hideOther() {"
//                            + "document.getElementsByTagName('body')[0].innerHTML;"
//                            + "document.getElementsByTagName('ul')[0].style.display='none';"
//                            + "document.getElementsByClassName('orderDetailNew orderDetailNewLi4')[0].style.display='none'};";
//                    //创建方法
//                    webView.loadUrl(title);
//                    webView.loadUrl(foot);
//
//                    //加载方法
//                    webView.loadUrl("javascript:hideTitle();");
////                    webView.loadUrl("javascript:hideOther();");
//                }
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (!TextUtils.isEmpty(bundleTitle)) {
                    toolbar_title.setText(bundleTitle);
                } else {
                    toolbar_title.setText(title);
                }
                webView.evaluateJavascript("javascript:getShare()",
                        value -> {
                            //此处为 js 返回的结果

                        });
            }
        });

        webView.setOnTouchListener((v, event) -> {
            webView.requestFocus();
            return false;
        });

        webView.addJavascriptInterface(new MyJavaScriptInterface(this), "SCNativeApp");
    }

    class MyJavaScriptInterface {
        private Context mContext;

        public MyJavaScriptInterface(Context context) {
            mContext = context;
        }

        //添加JS注解@JavascriptInterface。该Android原生的本地方法，供H5 Web网页调用。
        //该函数的访问属性必须是public。
        @JavascriptInterface
        public void jump(String type) {

            switch (type) {

            }
        }
    }
}